# coding: utf-8
from shangjie.utils import log, cache
from shangjie.utils import lunar
from shangjie.conf import settings
import datetime, time, hashlib

def check_code_valid(checkcode, phonenum):
    se = settings.DB_SESSION()
    try:
        """验证短信验证码是否有效"""
        code_sql = """select * from api_checkcode where checkcode='%s' and phonenum='%s'""" % (checkcode, phonenum)
        result = se.execute(code_sql.decode('utf-8')).fetchone()
        if not result:
            rspcode, rspinfo = 8002, '短信验证码不存在！'
        elif result.status == '1':
            rspcode, rspinfo = 8002, '验证码已使用！'
        else:
            # 判断验证码时间是否过期
            validtime_sql = """select * from api_parameter where paramcode='CheckCodeTimeout'"""
            validtime = se.execute(validtime_sql.decode('utf-8')).fetchone().paramvalue
            now = datetime.datetime.now()
            sjc = (now - datetime.datetime.strptime(result.applytime, "%Y%m%d%H%M%S")).seconds
            # 有效时间差，单位：秒
            if sjc > 60 * int(validtime):
                rspcode, rspinfo = 8002, '短信验证码过期！'
            else:
                rspcode, rspinfo = 0, 'OK'
                checkcode_sql = """update api_checkcode set status='1' where checkcode='%s' and phonenum='%s'""" % (checkcode, phonenum)
                se.execute(checkcode_sql.decode('utf-8'))
        se.close()
        return rspcode, rspinfo
    except Exception as e:
        se.close()
        raise e

def get_md5(password):
    m = hashlib.md5()
    m.update(password)
    return m.hexdigest()

def check_token_valid(tokenid):
    try:
        se = settings.DB_SESSION()
        token_sql = """select * from api_token where tokenid=%s""" % int(tokenid)
        token = se.execute(token_sql.decode('utf-8')).fetchone()
        if token:
            dqsj = datetime.datetime.now()
            sjc = (dqsj - datetime.datetime.strptime(token.createtime, "%Y%m%d%H%M%S")).seconds
            # 有效时间差，单位：秒
            if token.timelength != -1 and sjc > 60 * token.timelength:
                se.close()
                return False, ('[%s]已过期！' % str(token.tokenid))
            else:
                token_update = """update api_token set createtime='%s' where tokenid=%s""" % (dqsj.strftime("%Y%m%d%H%M%S"), int(tokenid))
                se.execute(token_update.decode('utf-8'))
                return True, token
        else:
            se.close()
            return False, '口令不存在，请重新登录！'
    except Exception as e:
        raise e

def str_to_stamp( timestr, fmtstr = "%Y%m%d%H%M%S" ):
    """将字符串转为时间戳数字"""
    timeArray = time.strptime(timestr, fmtstr )
    return int(time.mktime(timeArray))

def stamp_to_str( stamp, fmtstr="%Y%m%d%H%M%S"  ):
    """将时间戳数字转为字符串"""
    timeArray = time.localtime(int(stamp))
    return time.strftime(fmtstr, timeArray)